package org.example.springlogin.controller;

import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.springlogin.result.Result;
import org.example.springlogin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/10/14
 * Time: 14:39
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/login")
    public Result<String> login(String userName, String password, String captcha, HttpSession session) {
        log.info("接收到参数,userName:{},password:{},captcha:{}",userName,password,captcha);
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户或密码为空");
        }
        if (!StringUtils.hasLength(captcha)) {
            return Result.fail("验证码为空");
        }
        String result = userService.getUserInfoByUserName(userName, password, captcha, session);
        if (!result.equals("登录成功")){
            return Result.fail(result);
        }
        HashMap<String,String> map = new HashMap<>();
        map.put("userName",userName);
        map.put("password",password);
        //将map作为用户信息存储到session/会话中
        session.setAttribute("cookie", map);
        log.info("登录成功");
        return Result.success(result);
    }
}
